﻿package net.area80.serverside.activity.core
{
	import flash.events.DataEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	import flash.net.navigateToURL;
	import net.area80.serverside.errors.ErrorCodes;
	import net.area80.serverside.events.ServerSideEvent;
	import net.area80.serverside.ServerSide;
	import net.area80.serverside.datatype.SendVariable;
	
	/**
	* HTTPActivity
	* @author Wissarut Pimanmassuriya
	*/
	public class HTTPActivity extends AbstractServerActivity
	{
		
		
		protected var path:String;
		protected var testPath:String;
		protected var method:String;
		protected var urlTobeLoad:URLRequest;
		
		
		public function init (path:String, method:String = "GET", testPath:String = ""):void {
			this.method = method.toUpperCase();
			this.path = path;
			this.testPath = (testPath == "") ? path : testPath;
			urlTobeLoad =  new URLRequest(((ServerSide.useTestPath) ? this.testPath : this.path));
			urlTobeLoad.method = this.method;
		}
		
		
		public override function send (...datas):void {

			var urlLoader:URLLoader = new URLLoader();

			var urlVariables:URLVariables = new URLVariables();
			var i:int;
			if (datas.length > 0) {
				for (i = 0; i < datas.length; i++) {
						urlVariables[SendVariable.getSendVariable(datas[i]).name] = SendVariable.getSendVariable(datas[i]).data;
				}
			}
			if (ServerSide.cacheKill) {
				if (urlTobeLoad.method == "POST") {
					var nextPos:String;
					if (urlTobeLoad.url.indexOf("?") != -1) {
						nextPos = "&cacheKill=" + String(new Date().getTime());
					} else {
						nextPos = "?cacheKill=" + String(new Date().getTime());
					}
					urlTobeLoad.url = ((ServerSide.useTestPath) ? this.testPath + nextPos : this.path + nextPos);
				} else if (urlTobeLoad.method == "GET") {
					urlVariables["cacheKill"] = String(new Date().getTime());
				}
			}
			if (datas.length > 0) urlTobeLoad.data = urlVariables;
			
			configureListeners(urlLoader);
			
			doSendData(urlLoader);
		}
		
		
		protected function doSendData (urlLoader:URLLoader):void {
		//	navigateToURL(urlTobeLoad, "_blank");
			urlLoader.load(urlTobeLoad);
		}
		
		protected function configureListeners(dispatcher:IEventDispatcher):void {
            dispatcher.addEventListener(Event.COMPLETE, completeHandler);
            dispatcher.addEventListener(Event.OPEN, openHandler);
            dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
            dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
            dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
            dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
        }

        protected function completeHandler(event:Event):void {
            var loader:URLLoader = URLLoader(event.target);
            ServerSide.log("completeHandler: " + loader.data , ServerSide.DATATYPE_RECIEVED_DATA);
			processData(loader.data);
			dispatchEvent(new ServerSideEvent(Event.COMPLETE, URLLoader(event.target)));
        }

        protected function openHandler(event:Event):void {
            ServerSide.log("openHandler: " + event);
			dispatchEvent(new ServerSideEvent(Event.OPEN, URLLoader(event.target)));
        }

        protected function progressHandler(event:ProgressEvent):void {
            ServerSide.log("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
			dispatchEvent(new ServerSideEvent(ProgressEvent.PROGRESS, URLLoader(event.target)));
        }

        protected function securityErrorHandler(event:SecurityErrorEvent):void {
            ServerSide.log("securityErrorHandler: " + event);
			dispatchEvent(new ServerSideEvent(SecurityErrorEvent.SECURITY_ERROR, URLLoader(event.target), event.text));
        }

        protected function httpStatusHandler(event:HTTPStatusEvent):void {
            ServerSide.log("httpStatusHandler: " + event);
			dispatchEvent(new ServerSideEvent(HTTPStatusEvent.HTTP_STATUS, URLLoader(event.target), event.status));
			//doReload(URLLoader(event.target));
        }
		
		protected function ioErrorHandler(event:IOErrorEvent):void {
            ServerSide.log("ioErrorHandler: " + event);
			dispatchEvent(new ServerSideEvent(IOErrorEvent.IO_ERROR, URLLoader(event.target), event.text));
			doReload(URLLoader(event.target));
        }
		
		private function doReload (urlLoader:URLLoader):void {
			if (reloadIfFailed) {
				ServerSide.log("Reload");
				doSendData(urlLoader);
			}
		}
		
	}
	
}